package app.controllers;

import app.Const;
import app.models.product.Issuer;
import com.google.common.base.Strings;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import goja.mvc.Controller;
import goja.rapid.datatables.DTCriterias;
import goja.rapid.db.DaoKit;
import org.joda.time.DateTime;

/**
 * <p>
 * 发行机构管理
 * </p>
 *
 * @author liuhui
 * @version 1.0
 * @since JDK 1.6
 */
public class IssuerController extends Controller {

    /**
     * The index route.
     * the url /issuer
     * the view in index.ftl.html
     */
    @Before(GET.class)
    public void index() {
    }

    /**
     * 列表访问
     */
    @Before(GET.class)
    public void dtlist() {
        final DTCriterias criterias = DTCriterias.criteriasWithRequest(getRequest());
        renderDataTables(criterias, Issuer.class);
    }

    @Before(GET.class)
    public void create() {
        Issuer issuer = new Issuer();
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        setAttr(issuer);
        render("item.ftl");
    }

    @Before(GET.class)
    public void edit() {
        String id = getPara(0, "0");
        Issuer issuer = Issuer.dao.findById(id);
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        setAttr("issuer", issuer);
        render("item.ftl");
    }

    @Before(POST.class)
    public void save() {
        Issuer issuer = getModel(Issuer.class);

        if (!Strings.isNullOrEmpty(getPara("pic_attachment"))) {
            issuer.set("logo", getPara("pic_attachment_url"));
            issuer.set("logo_attachment", getPara("pic_attachment"));
        }

        if (DaoKit.isNew(issuer)) {
            issuer.set("join_time", DateTime.now().toDate());
            issuer.set(Const.FIELD_CREATE_TIME, DateTime.now().toDate());
            issuer.save();
        } else {
            issuer.update();
        }
        redirect("/issuer");
    }

    public void delete() {
        int id = getParaToInt(0, 0);
        boolean status = Issuer.dao.deleteById(id);
        if (status) {
            renderAjaxSuccess();
        } else {
            renderAjaxFailure();
        }
    }
}
